package com.doge.calcalbum.business.vip

import android.os.Handler
import android.os.Looper
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.doge.calcalbum.api.*
import com.doge.calcalbum.api.model.DiscountInfo
import com.doge.calcalbum.api.model.OrderInfo
import com.doge.calcalbum.api.model.ProductInfo
import com.doge.calcalbum.api.model.VipPaymentInfo
import com.doge.calcalbum.core.base.LoadStatus
import com.doge.calcalbum.utils.isMainThread
import kotlin.math.max

class VipBuyViewModel : ViewModel() {
    val loading = MutableLiveData<LoadStatus>()
    val productList = MutableLiveData<List<ProductInfo>>()
    val discountInfo = MutableLiveData<DiscountInfo?>()
    val order = MutableLiveData<OrderInfo?>()

    fun request() {
        require(isMainThread())
        if (productList.value?.isNotEmpty() != true) loading.value = LoadStatus.LOADING

        api
            .productListV2()
            .map(ApiResultMapTransformer())
            .subscribeOnIO()
            .observeOnMain()
            .subscribe(object : ObserverAdapter<VipPaymentInfo>() {
                override fun onNext(t: VipPaymentInfo) {
                    productList.value = t.productList ?: listOf()
                    discountInfo.value = t.discount
                    handler.removeMessages(msgCountdownTask)
                    handler.sendEmptyMessageDelayed(msgCountdownTask, 1000)
                    loading.value = LoadStatus.SUCCESS
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    loading.value = LoadStatus.FAILURE
                }
            })
    }

    fun buy(product: ProductInfo?, payType: Int) {
        if (product == null) return
        api
            .createOrder(product.productId, payType)
            .map(ApiResultMapTransformer())
            .subscribeOnIO()
            .observeOnMain()
            .subscribe(object : ObserverAdapter<OrderInfo>() {
                override fun onNext(t: OrderInfo) {
                    order.value = t
                    order.value = null
                }
            })
    }


    private val msgCountdownTask = 101
    private val handler = Handler(Looper.getMainLooper()) {
        if (it.what == msgCountdownTask) {
            it.target.removeMessages(msgCountdownTask)
            val lastLeftTime = discountInfo.value?.leftTime ?: 0L
            if (lastLeftTime > 0) {
                discountInfo.value = discountInfo.value?.copy(
                    leftTime = max(0, lastLeftTime - 1000)
                )
                it.target.sendEmptyMessageDelayed(msgCountdownTask, 1000)
            }
        }
        true
    }
}